package org.odk.aggregate.personfindermobile;

import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * Abstraction that allows us to retrieve the form submissions that were sent in
 * a first in first out order.
 * 
 * @author Marc Stogaitis
 */
public class FormSubmissionQueue {

  /**
   * Returns the oldest form submission that has been added to the database for
   * a specified form.
   * 
   * @param formName
   *          name of the form for which to retrieve the data.
   * @return the oldest database entry for this form, or {@code null} if none
   *         exist.
   */
  public Entity getHead(String formName) {

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query(formName);
    query.addSort("__key__");

    PreparedQuery preparedQuery = ds.prepare(query);
    FetchOptions options = FetchOptions.Builder.withLimit(1);

    List<Entity> list = preparedQuery.asList(options);
    if (list.size() != 1) {
      return null;
    }
    return list.get(0);
  }

  /**
   * Deletes an entity from the database.
   * 
   * @param entity
   *          the entity to delete.
   */
  public void deleteFromQueue(Entity entity) {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    ds.delete(entity.getKey());
  }
}
